package com.appspot.urlheap.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.urlheap.data.Item;
import com.appspot.urlheap.data.PMF;
import com.appspot.urlheap.tmpl.TemplateProcessor;

public class IndexServlet extends BaseServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		super.doGet(req, resp);

		Map<String, Object> values = getValues();

		if (getUser() == null) {
			TemplateProcessor.process("first.ftl", values, resp.getWriter());
			return;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Item.class.getName() + " where user == '" + getUser().getEmail() + "' order by date desc";
		List<Item> result = (List<Item>) pm.newQuery(query).execute();
		List<Item> items = new ArrayList<Item>(result);

		String pRnd = req.getParameter("shuffle");
		if (pRnd != null && Boolean.valueOf(pRnd)) {
			Collections.shuffle(items);
			values.put("shuffle", "false");
		} else {
			values.put("shuffle", "true");
		}

		values.put("items", items);

		if (items.size() > 0) {
			List<String> dates = new ArrayList<String>(items.size());
			long curDate = System.currentTimeMillis();
			long sec = 1000;
			long min = 60 * sec;
			long hour = 60 * min;
			long day = 24 * hour;
			for (Item item : items) {
				long diff = curDate - item.getDate();
				long days = diff / day;
				if (days > 0) {
					dates.add(days + " days");
					continue;
				}
				long hours = diff % day / hour;
				if (hours > 0) {
					dates.add(hours + " hours");
					continue;
				}
				long mins = diff % day % hour / min;
				if (mins > 0) {
					dates.add(mins + " mins");
					continue;
				}
				dates.add("some seconds");
			}
			values.put("dates", dates);
		}

		TemplateProcessor.process("index.ftl", values, resp.getWriter());
	}
}
